import hashlib
import json
import random
import string
import yaml
import os
import time
from datetime import datetime, timedelta


class Util(object):
    @staticmethod
    def read_yaml_config(file_path):
        with open(file_path, 'r') as f:
            cfg = yaml.load(f.read(), Loader=yaml.FullLoader)
            return cfg

    def get_db_config(self, service):
        root_path = os.path.split(os.path.dirname(__file__))[0]
        file_path = os.path.join(root_path, 'config', 'db_conf.yaml')
        cfg = self.read_yaml_config(file_path)[service]
        return cfg

    @staticmethod
    def get_time_stamp(days=None):
        if not days:
            return int(round(time.time() * 1000))
        else:
            day = datetime.now().replace(microsecond=0) + timedelta(days=days)
            ts = int(time.mktime(time.strptime(str(day), '%Y-%m-%d %H:%M:%S'))) * 1000
            return ts

    @staticmethod
    def generate_name(length=8):
        ran_str = ''.join(random.sample(string.ascii_letters + string.digits, length))
        return ran_str

    @staticmethod
    def convert_to_dict(string_obj):
        return json.loads(string_obj)

    @staticmethod
    def str_assert(str_obj, other_str_obj):
        try:
            assert str(str_obj) == str(other_str_obj)
        except AssertionError:
            raise AssertionError(f'{str_obj} != {other_str_obj}')

    @staticmethod
    def get_json_data_by_name(file_path):
        with open(file_path, 'r') as f:
            return json.loads(f.read())

    @staticmethod
    def get_version():
        return os.environ['VERSION']

    @staticmethod
    def get_sign(user_name, pass_word):
        time_str = str(round(time.time() * 1000))
        string_obj = f'app_login{user_name}{pass_word}{time_str})'
        md5_obj = hashlib.md5(string_obj.encode("utf-8"))
        return md5_obj.hexdigest()

    def get_user_info(self):
        env = os.environ['ENV']
        config = self.get_db_config('env').get(env)
        user_name = str(config.get('username'))
        pass_word = str(config.get('password'))
        return user_name, pass_word

    @staticmethod
    def get_token_by_env():
        env = os.environ['ENV']
        token = '460768F1A5D674C1A72DB9A98A808D265C3F9762D45D2B32AE2432366C97026A0E089C0431152FA8D5D79AFCC1DB68E3D65DF8583CA7A8798CB8EAFA85B8A9C25B4F75B0F49C5D05D6FBC7F445EBDCF10FFB00AA16D568744C37ADB73700245182652E5EB4BEC412B7E10D4444CB50D645E6A70903C284C76A63DDCE54405A4D6D8FDA4B0B36BFA7EF5F14F1' \
            if env != 'test' else ''
        return token

    @staticmethod
    def get_env():
        return os.environ['ENV']

    def get_url_by_name(self, service, name):
        service_new = ''.join(service[:1].lower() + service[1:])
        json_path = os.path.join(os.path.split(os.path.dirname(__file__))[0], 'config', 'service_conf.yaml')
        cfg = self.read_yaml_config(json_path).get(service_new).get(name)
        return cfg
